import { Card, Button, Select, Input, Table, Tag, Modal } from 'antd';
import { useEffect, useState } from 'react';
import { useRequest } from 'umi';
import type { ColumnsType } from 'antd/es/table';
import { useSetState } from 'react-use';
import { NamespaceService } from '../namespace/service';
import { DeployService } from './service';
import Deploy, { ListReq, ListResp } from './vms';
import DeployDetail from './components/details';
import Pods, { Props as PodProps } from './components/pods'

import styles from './index.less';

export default function DeployIndex() {
  const [filter, setFilter] = useSetState<ListReq>({});
  const [name, setName] = useState<string>('');
  const [isCreate, setIsCreate] = useState<boolean>(true);
  const [podProps, setPodProps] = useSetState<PodProps>({
    open: false,
    namespace: '',
    deploy_name: '',
  })

  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [editDeploy, setEditDeploy] = useState<Deploy>();

  const [resp, setResp] = useSetState<ListResp>({ total: 0, items: [] });

  const handleChange = (namespace: string) => {
    setFilter({ namespace });
  };

  const list = useRequest(DeployService.list, {
    manual: true,
    onSuccess: (data) => {
      setResp(data);
    },
  });

  const deleteFunc = useRequest(DeployService.delete, {
    manual: true,
    onSuccess: () => {
      list.refresh();
    },
  });

  const [options, setOptions] = useState<
    {
      value: string;
      label: string;
    }[]
  >();
  const columns: ColumnsType<Deploy> = [
    {
      title: '部署名称',
      dataIndex: 'deploy_name',
      key: 'deploy_name',
    },
    {
      title: '名称空间',
      dataIndex: 'namespace',
      key: 'namespace',
    },
    {
      title: '副本集',
      dataIndex: 'replicas',
      key: 'replicas',
      render: (_, { deployment }) => deployment.spec.replicas,
    },
    {
      title: '镜像服务',
      dataIndex: 'containers',
      key: 'containers',
      render: (_, { deployment }) =>
        deployment.spec.template.spec.containers.map((item) => (
          <Tag key={item.image}>{`${item.image}-${item.ports.map(
            (i) => `(${i.name}-${i.protocol}-${i.containerPort}`,
          )})`}</Tag>
        )),
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <div style={{ display: 'flex' }}>

          <Button
            style={{ padding: '0 4px' }}
            type="link"
            onClick={() => {
              setIsCreate(false)
              setShowDetail(true)
              // @ts-ignore
              setEditDeploy(record)
            }}
          >
            详情
          </Button>
          <Button
            style={{ padding: '0 4px' }}
            type="link"
            onClick={() => {
              setPodProps({ open: true, namespace: record.namespace, deploy_name: record.deploy_name })
            }}
          >
            Pod
          </Button>
          <Button
            style={{ padding: '0 4px' }}
            type="link"
            onClick={() => {
              Modal.confirm({
                title: '删除Deploy!',
                content: '删除是不可逆操作',
                cancelText: '取消',
                okText: '确定删除',
                onOk: () => {
                  return deleteFunc.run({
                    name: record.deploy_name,
                    namespace: record.namespace,
                  });
                },
              });
            }}
          >
            删除
          </Button>
        </div>
      ),
    },
  ];
  useEffect(() => {
    NamespaceService.list().then((res) => {
      setOptions(
        res.data?.names?.map((name) => ({
          value: name,
          label: name,
        })),
      );
    });
  }, []);

  useEffect(() => {
    list.run(filter);
  }, [filter]);

  return (
    <>
      <DeployDetail
        isCreate={isCreate}
        open={showDetail}
        onClose={() => setShowDetail(false)}
        namespaces={options}
        onSuccess={list.refresh}
        record={editDeploy}
      />
      <Pods {...podProps} onCancel={() => setPodProps({ open: false, namespace: '', deploy_name: '' })} />

      <Card
        className={styles.deploy}
        title={
          <>
            <Select
              style={{ width: 120 }}
              value={filter.namespace}
              onChange={handleChange}
              placeholder="namespace"
              allowClear
              options={options}
            />

            <Input
              value={name}
              className={styles.inputName}
              placeholder="输入关键词"
              onChange={(e) => setName(e.target.value)}
              // @ts-ignore
              onPressEnter={(e) => setFilter({ name: e.target.value })}
            />
          </>
        }
        extra={
          <Button type="link" onClick={() => {
            setIsCreate(true)
            setShowDetail(true)
          }}>
            新建部署
          </Button>
        }
      >
        <Table
          rowKey={(record) => JSON.stringify(record)}
          columns={columns}
          loading={list.loading}
          dataSource={resp.items}
          pagination={{
            total: resp.total,
            pageSize: 20,
          }}
        />
      </Card>
    </>
  );
}
